import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:merchants/enum/spu_status.dart';
import 'package:merchants/models/sku.dart';
import 'package:merchants/models/spu.dart';
import 'package:merchants/models/spu_category.dart';
import 'package:merchants/providers/providers.dart';
import 'package:merchants/widgets/image_picker_widget.dart';

class SpuFormPage extends ConsumerStatefulWidget {
  final String? spuId;

  const SpuFormPage({super.key, this.spuId});

  @override
  SpuFormPageState createState() => SpuFormPageState();
}

class SpuFormPageState extends ConsumerState<SpuFormPage> {
  final _formKey = GlobalKey<FormState>();
  String _name = '';
  String _category = '';
  String _description = '';
  SpuStatus _status = SpuStatus.toEnable;

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();
  late Future<List<SpuCategory>> _categoriesFuture;
  bool _isLoading = false;

  final List<Map<String, dynamic>> _attrNames = [];
  List<File> _images = [];
  final Map<String, String?> _selectedSpecValues = {};
  final List<Map<String, dynamic>> _skus = [];
  final TextEditingController _stockController = TextEditingController();
  final TextEditingController _priceController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _categoriesFuture = ref.read(categoryServiceProvider).getList();
    _stockController.text = '1000';
    _priceController.text = '0.00';
    _category = '';
    if (widget.spuId != null) {
      _loadSpuData();
    } else {
      // 创建模式下，初始化一个默认的 SKU
      _skus.add({
        'price': 0.0,
        'stock': 1000,
        'specs': null,
        'image': null,
      });
    }
  }

  // 加载 SPU 和 SKU 数据（编辑模式）
  Future<void> _loadSpuData() async {
    setState(() => _isLoading = true);
    try {
      // 加载 SPU
      final spu = await ref.read(spuServiceProvider).getSpuById(widget.spuId!);
      setState(() {
        _name = spu.name;
        _nameController.text = spu.name;
        _category = spu.cate.isNotEmpty ? spu.cate[0] : '';
        _description = spu.detail ?? '';
        _descriptionController.text = spu.detail ?? '';
        _status = spu.status;
        _images = []; // 暂不初始化图片，需用户重新上传
      });

      // 加载 SKU
      final skus = await ref
          .read(skuServiceProvider)
          .getList(spuId: widget.spuId!);
      setState(() {
        _skus.clear();
        for (var sku in skus) {
          final specs =
              sku.attrValue?.asMap().entries.map((entry) {
                return {
                  'id': 'spec_${entry.key}',
                  'name': '规格${entry.key + 1}',
                  'value': entry.value,
                };
              }).toList();
          _skus.add({
            'specs': specs,
            'stock': sku.count,
            'price': sku.price,
            'image': sku.image,
          });
        }
        _attrNames.clear();
        if (_skus.isNotEmpty && _skus[0]['specs'] != null) {
          final firstSkuSpecs = _skus[0]['specs'] as List<Map<String, dynamic>>;
          for (var spec in firstSkuSpecs) {
            _attrNames.add({
              'id': spec['id'],
              'name': spec['name'],
              'tags':
                  _skus
                      .map(
                        (sku) =>
                            (sku['specs'] as List<Map<String, dynamic>>)
                                .firstWhere(
                                  (s) => s['id'] == spec['id'],
                                )['value'],
                      )
                      .toSet()
                      .toList(),
            });
          }
        } else if (_skus.isNotEmpty) {
          // 如果没有规格，初始化一个默认的 SKU
          _skus.clear();
          _skus.add({
            'price': 0.0,
            'stock': 1000,
            'specs': null,
            'image': null,
          });
        }
        // 初始化库存和价格控制器
        if (_skus.isNotEmpty) {
          _stockController.text = _skus[0]['stock'].toString();
          _priceController.text = _skus[0]['price']?.toString() ?? '0.00';
        } else {
          // 如果没有 SKU，使用默认值
          _stockController.text = '1000';
          _priceController.text = '0.00';
        }
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('加载数据失败: $e')));
      }
    }
    if (mounted) {
      setState(() => _isLoading = false);
    }
  }

  bool _areAllSpecsSelected() {
    if (_attrNames.isEmpty) return false;
    return _attrNames.every((spec) {
      final specId = spec['id'] as String;
      return _selectedSpecValues[specId] != null;
    });
  }

  @override
  void dispose() {
    _nameController.dispose();
    _descriptionController.dispose();
    _stockController.dispose();
    _priceController.dispose();
    super.dispose();
  }

  void _resetForm() {
    if (mounted && _formKey.currentState != null) {
      _formKey.currentState!.reset();
      _nameController.clear();
      _descriptionController.clear();
      setState(() {
        _name = '';
        _category = '';
        _description = '';
        _status = SpuStatus.toEnable;
        _attrNames.clear();
        _images.clear();
        _selectedSpecValues.clear();
        _skus.clear();
        _stockController.text = '1000';
        _priceController.text = '0.00';
        // 重新初始化默认的 SKU
        if (widget.spuId == null) {
          _skus.add({
            'price': 0.0,
            'stock': 1000,
            'specs': null,
            'image': null,
          });
        }
      });
    }
  }

  List<List<String>> _getAllSpecCombinations() {
    if (_attrNames.isEmpty) return [];

    List<List<String>> specValues =
        _attrNames.map((spec) {
          return (spec['tags'] as List<dynamic>?)?.cast<String>() ?? [];
        }).toList();

    List<List<String>> combinations = [[]];
    for (var values in specValues) {
      List<List<String>> newCombinations = [];
      for (var combination in combinations) {
        for (var value in values) {
          newCombinations.add([...combination, value]);
        }
      }
      combinations = newCombinations;
    }

    return combinations;
  }

  void _updateSkusWithDefaultStock() {
    final allCombinations = _getAllSpecCombinations();
    setState(() {
      final existingSkuMap = Map.fromEntries(
        _skus.map(
          (sku) => MapEntry(
            (sku['specs'] as List<Map<String, dynamic>>)
                .map((spec) => spec['value'])
                .join(','),
            sku,
          ),
        ),
      );

      _skus.clear();
      for (var combination in allCombinations) {
        final key = combination.join(',');
        final specCombination =
            _attrNames.asMap().entries.map((entry) {
              final index = entry.key;
              final spec = entry.value;
              return {
                'id': spec['id'],
                'name': spec['name'],
                'value': combination[index],
              };
            }).toList();

        final existingSku = existingSkuMap[key];
        _skus.add({
          'specs': specCombination,
          'stock': existingSku != null ? existingSku['stock'] : 1000,
          'price': existingSku != null ? existingSku['price'] : null,
          'image': existingSku != null ? existingSku['image'] : null,
        });
      }
    });
  }

  bool _checkAllCombinationsHaveImage(List<List<String>> combinations) {
    if (combinations.isEmpty) return true;

    for (var combination in combinations) {
      bool found = _skus.any((sku) {
        final specs = sku['specs'] as List<Map<String, dynamic>>;
        return specs.length == combination.length &&
            specs.every((spec) => combination.contains(spec['value']));
      });

      if (!found ||
          (found && _skus.every((sku) => (sku['image'] as String?) == null))) {
        return false;
      }
    }
    return true;
  }

  bool _checkAllCombinationsHavePrice(List<List<String>> combinations) {
    if (combinations.isEmpty) return true;

    for (var combination in combinations) {
      bool found = _skus.any((sku) {
        final specs = sku['specs'] as List<Map<String, dynamic>>;
        return specs.length == combination.length &&
            specs.every((spec) => combination.contains(spec['value']));
      });

      if (!found ||
          (found && _skus.every((sku) => (sku['price'] as double?) == null))) {
        return false;
      }
    }
    return true;
  }

  Future<void> _submitForm() async {
    if (_formKey.currentState!.validate()) {
      // 检查是否有图片（如果没有图片，使用默认图片）
      if (_images.isEmpty) {
        // 使用默认图片URL
        _images = [];
      }

      _formKey.currentState!.save();

      // 检查规格和价格及图片
      if (_attrNames.isNotEmpty) {
        final allCombinations = _getAllSpecCombinations();
        if (!_checkAllCombinationsHavePrice(allCombinations)) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('请为所有规格组合设置价格')));
          return;
        }
        if (!_checkAllCombinationsHaveImage(allCombinations)) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('请为所有规格组合选择图片')));
          return;
        }
      } else {
        final defaultPrice = _priceController.text.trim();
        final defaultStock = _stockController.text.trim();
        if (defaultPrice.isEmpty || defaultStock.isEmpty) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('请设置库存和价格')));
          return;
        }

        final priceValue = double.tryParse(defaultPrice);
        final stockValue = int.tryParse(defaultStock);

        if (priceValue == null || priceValue < 0) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('请输入有效的价格（大于等于0）')));
          return;
        }
        if (stockValue == null || stockValue < 0) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('请输入有效的库存（大于等于0）')));
          return;
        }

        _skus.clear();
        _skus.add({
          'price': priceValue,
          'stock': stockValue,
          'specs': null,
          'image': _images.isNotEmpty ? _images.first.path : null,
        });
      }

      setState(() => _isLoading = true);
      try {
        // 处理图片
        List<String> validImageUrls = [];
        if (_images.isNotEmpty) {
          // 上传图片
          final imageUrls = await ref
              .read(commonUploadServiceProvider)
              .uploadImages(_images, directory: 'spu_images');
          validImageUrls = imageUrls.isNotEmpty ? imageUrls : [];
        } else {
          // 使用默认图片
          validImageUrls = ['https://via.placeholder.com/400x300?text=${Uri.encodeComponent(_name)}'];
        }

        // 创建或更新 SPU
        final spu = Spu(
          id: widget.spuId,
          cate: [_category],
          swiperImages: validImageUrls,
          name: _name,
          detail: _description,
          status: _status,
          priority: 0,
          coverImage: validImageUrls.isNotEmpty ? validImageUrls.first : '',
        );

        String spuId;
        if (widget.spuId == null) {
          // 新增
          spuId = await ref.read(spuServiceProvider).createSpu(spu);
        } else {
          // 编辑
          await ref.read(spuServiceProvider).updateSpu(spu);
          spuId = widget.spuId!;
          // 删除旧 SKU
          final existingSkus = await ref
              .read(skuServiceProvider)
              .getList(spuId: spuId);
          for (var sku in existingSkus) {
            await ref.read(skuServiceProvider).delete(sku.id!);
          }
        }

        // 创建或更新 SKU
        for (var sku in _skus) {
          final specs = sku['specs'] as List<Map<String, dynamic>>?;
          final stock = sku['stock'] as int;
          final price = sku['price'] as double;
          final image = sku['image'] as String?;

          final List<String> attrValues =
              specs?.map((spec) => spec['value'] as String).toList() ?? [];
          final newSku = Sku(
            count: stock,
            price: price,
            attrValue: attrValues,
            image: image != null
                ? (specs != null
                    ? validImageUrls[_images.indexWhere(
                        (img) => img.path == image,
                      )]
                    : validImageUrls.isNotEmpty
                        ? validImageUrls.first
                        : null)
                : null,
            description: null,
          );
          await ref.read(skuServiceProvider).create(sku: newSku, spuId: spuId);
        }

        // 成功提示并返回
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(widget.spuId == null ? '添加成功' : '更新成功')),
          );
          context.go('/tabs/spu/list');
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('操作失败: $e')));
        }
      }
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _addAttrName() async {
    final List<Map<String, dynamic>>? selectedAttrNames = await context.push(
      '/attr-name/list',
      extra: {'selectedAttrNames': _attrNames},
    );
    if (selectedAttrNames != null) {
      setState(() {
        for (var newSpec in selectedAttrNames) {
          final specId = newSpec['id'] as String;
          final existingIndex = _attrNames.indexWhere(
            (spec) => spec['id'] == specId,
          );
          if (existingIndex == -1) {
            _attrNames.add(newSpec);
          } else {
            _attrNames[existingIndex] = newSpec;
          }
        }
        _attrNames.retainWhere(
          (spec) =>
              selectedAttrNames.any((newSpec) => newSpec['id'] == spec['id']),
        );
        _updateSkusWithDefaultStock();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.spuId == null ? '添加商品' : '编辑商品'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => context.go('/tabs/spu/list'),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        centerTitle: true,
      ),
      body:
          _isLoading
              ? const Center(child: CircularProgressIndicator())
              : Padding(
                padding: const EdgeInsets.all(16.0),
                child: Form(
                  key: _formKey,
                  child: ListView(
                    children: [
                      const SizedBox(height: 8),
                      TextFormField(
                        controller: _nameController,
                        decoration: const InputDecoration(
                          labelText: '名称*',
                          border: OutlineInputBorder(),
                        ),
                        validator:
                            (value) =>
                                value == null || value.isEmpty
                                    ? '名称不能为空'
                                    : null,
                        onSaved: (value) => _name = value!,
                      ),
                      const SizedBox(height: 16),
                      FutureBuilder<List<SpuCategory>>(
                        future: _categoriesFuture,
                        builder: (context, snapshot) {
                          if (snapshot.connectionState ==
                              ConnectionState.waiting) {
                            return const Center(
                              child: CircularProgressIndicator(),
                            );
                          } else if (snapshot.hasError) {
                            return Column(
                              children: [
                                Text('加载分类失败: ${snapshot.error}'),
                                const SizedBox(height: 8),
                                ElevatedButton(
                                  onPressed: () {
                                    setState(() {
                                      _categoriesFuture =
                                          ref
                                              .read(categoryServiceProvider)
                                              .getList();
                                    });
                                  },
                                  child: const Text('重试'),
                                ),
                              ],
                            );
                          } else if (!snapshot.hasData ||
                              snapshot.data!.isEmpty) {
                            return const Text('暂无分类数据');
                          } else {
                            final categories = snapshot.data!;
                            return DropdownButtonFormField<String>(
                              value: _category.isNotEmpty ? _category : null,
                              decoration: const InputDecoration(
                                labelText: '分类*',
                                border: OutlineInputBorder(),
                              ),
                              items:
                                  categories.map((SpuCategory category) {
                                    return DropdownMenuItem<String>(
                                      value: category.id,
                                      child: Text(category.name),
                                    );
                                  }).toList(),
                              validator:
                                  (value) => value == null ? '分类不能为空' : null,
                              onChanged: (value) {
                                setState(() {
                                  _category = value ?? '';
                                });
                              },
                              onSaved: (value) => _category = value!,
                            );
                          }
                        },
                      ),
                      const SizedBox(height: 16),
                      ImagePickerWidget(
                        onImagesSelected: (images) {
                          setState(() {
                            _images = images;
                          });
                        },
                      ),
                      // 规格区域
                      const SizedBox(height: 16),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children:
                            _attrNames.map((spec) {
                              final specId = spec['id'] as String;
                              final tags =
                                  (spec['tags'] as List<dynamic>?)
                                      ?.cast<String>() ??
                                  [];
                              return Padding(
                                padding: const EdgeInsets.only(bottom: 8.0),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      spec['name'] as String,
                                      style: const TextStyle(
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    const SizedBox(height: 8),
                                    if (tags.isEmpty)
                                      const Text(
                                        '暂无规格值',
                                        style: TextStyle(color: Colors.grey),
                                      )
                                    else
                                      Wrap(
                                        spacing: 8,
                                        children:
                                            tags.map((tag) {
                                              final isSelected =
                                                  _selectedSpecValues[specId] ==
                                                  tag;
                                              return ChoiceChip(
                                                label: Text(tag),
                                                selected: isSelected,
                                                onSelected: (selected) {
                                                  setState(() {
                                                    if (selected) {
                                                      _selectedSpecValues[specId] =
                                                          tag;
                                                      if (_areAllSpecsSelected()) {
                                                        final existingSkuIndex =
                                                            _skus.indexWhere((
                                                              sku,
                                                            ) {
                                                              final specs =
                                                                  sku['specs']
                                                                      as List<
                                                                        Map<
                                                                          String,
                                                                          dynamic
                                                                        >
                                                                      >;
                                                              return specs.every((
                                                                spec,
                                                              ) {
                                                                final specId =
                                                                    spec['id']
                                                                        as String;
                                                                return _selectedSpecValues[specId] ==
                                                                    spec['value'];
                                                              });
                                                            });

                                                        if (existingSkuIndex !=
                                                            -1) {
                                                          _stockController
                                                                  .text =
                                                              _skus[existingSkuIndex]['stock']
                                                                  .toString();
                                                          _priceController
                                                                  .text =
                                                              _skus[existingSkuIndex]['price']
                                                                  ?.toString() ??
                                                              '';
                                                        } else {
                                                          _stockController
                                                              .clear();
                                                          _priceController
                                                              .clear();
                                                        }
                                                      }
                                                    } else {
                                                      _selectedSpecValues[specId] =
                                                          null;
                                                      _stockController.clear();
                                                      _priceController.clear();
                                                    }
                                                  });
                                                },
                                                selectedColor: const Color(
                                                  0xFF1A73E8,
                                                ).withOpacity(0.2),
                                                backgroundColor: Colors.grey
                                                    .withOpacity(0.1),
                                              );
                                            }).toList(),
                                      ),
                                  ],
                                ),
                              );
                            }).toList(),
                      ),
                      SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          onPressed: _addAttrName,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: const Color(0xFF1A73E8),
                            foregroundColor: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                            elevation: 0,
                          ),
                          child: const Text('添加规格'),
                        ),
                      ),
                      const SizedBox(height: 16),
                      Row(
                        children: [
                          Expanded(
                            child: TextField(
                              controller: _stockController,
                              decoration: const InputDecoration(
                                labelText: '库存*',
                                border: OutlineInputBorder(),
                              ),
                              enabled:
                                  _attrNames.isEmpty || _areAllSpecsSelected(),
                              keyboardType: TextInputType.number,
                              inputFormatters: [
                                FilteringTextInputFormatter.digitsOnly,
                                TextInputFormatter.withFunction((
                                  oldValue,
                                  newValue,
                                ) {
                                  final text = newValue.text;
                                  if (text.isEmpty) return newValue;
                                  final value = int.tryParse(text);
                                  if (value == null ||
                                      value < 0 ||
                                      value > 999999) {
                                    return oldValue;
                                  }
                                  return newValue;
                                }),
                              ],
                              onChanged: (value) {
                                if (_areAllSpecsSelected()) {
                                  final stock = int.tryParse(value) ?? 1000;
                                  final price = double.tryParse(
                                    _priceController.text,
                                  );
                                  final specCombination =
                                      _attrNames.map((spec) {
                                        final specId = spec['id'] as String;
                                        return {
                                          'id': specId,
                                          'name': spec['name'],
                                          'value': _selectedSpecValues[specId],
                                        };
                                      }).toList();

                                  setState(() {
                                    final existingSkuIndex = _skus.indexWhere((
                                      sku,
                                    ) {
                                      final specs =
                                          sku['specs']
                                              as List<Map<String, dynamic>>;
                                      return specs.every(
                                        (spec) =>
                                            _selectedSpecValues[spec['id']] ==
                                            spec['value'],
                                      );
                                    });

                                    if (existingSkuIndex != -1) {
                                      _skus[existingSkuIndex]['stock'] = stock;
                                      if (price != null) {
                                        _skus[existingSkuIndex]['price'] =
                                            price;
                                      }
                                    } else {
                                      _skus.add({
                                        'specs': specCombination,
                                        'stock': stock,
                                        'price': price,
                                        'image': null,
                                      });
                                    }
                                  });
                                }
                              },
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: TextField(
                              controller: _priceController,
                              decoration: const InputDecoration(
                                labelText: '价格*',
                                border: OutlineInputBorder(),
                              ),
                              enabled:
                                  _attrNames.isEmpty || _areAllSpecsSelected(),
                              keyboardType:
                                  const TextInputType.numberWithOptions(
                                    decimal: true,
                                  ),
                              inputFormatters: [
                                FilteringTextInputFormatter.allow(
                                  RegExp(r'[0-9.]'),
                                ),
                                TextInputFormatter.withFunction((
                                  oldValue,
                                  newValue,
                                ) {
                                  final text = newValue.text;
                                  if (text.isEmpty) return newValue;
                                  if (text.split('.').length > 2)
                                    return oldValue;
                                  if (text.contains('.')) {
                                    final parts = text.split('.');
                                    if (parts.length == 2 &&
                                        parts[1].length > 2) {
                                      return oldValue;
                                    }
                                  }
                                  final value = double.tryParse(text);
                                  if (value == null ||
                                      value < 0 ||
                                      value > 999999) {
                                    return oldValue;
                                  }
                                  return newValue;
                                }),
                              ],
                              onChanged: (value) {
                                if (_areAllSpecsSelected()) {
                                  final price = double.tryParse(value);
                                  final stock =
                                      int.tryParse(_stockController.text) ??
                                      1000;
                                  final specCombination =
                                      _attrNames.map((spec) {
                                        final specId = spec['id'] as String;
                                        return {
                                          'id': specId,
                                          'name': spec['name'],
                                          'value': _selectedSpecValues[specId],
                                        };
                                      }).toList();

                                  setState(() {
                                    final existingSkuIndex = _skus.indexWhere((
                                      sku,
                                    ) {
                                      final specs =
                                          sku['specs']
                                              as List<Map<String, dynamic>>;
                                      return specs.every(
                                        (spec) =>
                                            _selectedSpecValues[spec['id']] ==
                                            spec['value'],
                                      );
                                    });

                                    if (existingSkuIndex != -1) {
                                      _skus[existingSkuIndex]['price'] = price;
                                      _skus[existingSkuIndex]['stock'] = stock;
                                    } else {
                                      _skus.add({
                                        'specs': specCombination,
                                        'stock': stock,
                                        'price': price,
                                        'image': null,
                                      });
                                    }
                                  });
                                }
                              },
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 16),
                      if (_attrNames.isNotEmpty && _areAllSpecsSelected())
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Text(
                              '当前规格组合图片*',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 8),
                            DropdownButtonFormField<String>(
                              decoration: const InputDecoration(
                                labelText: '选择图片',
                                border: OutlineInputBorder(),
                              ),
                              items:
                                  _images.map((File image) {
                                    return DropdownMenuItem<String>(
                                      value: image.path,
                                      child: Row(
                                        children: [
                                          Image.file(
                                            image,
                                            width: 40,
                                            height: 40,
                                            fit: BoxFit.cover,
                                          ),
                                          const SizedBox(width: 8),
                                          Text(image.path.split('/').last),
                                        ],
                                      ),
                                    );
                                  }).toList(),
                              onChanged: (String? value) {
                                if (value != null && _areAllSpecsSelected()) {
                                  final specCombination =
                                      _attrNames.map((spec) {
                                        final specId = spec['id'] as String;
                                        return {
                                          'id': specId,
                                          'name': spec['name'],
                                          'value': _selectedSpecValues[specId],
                                        };
                                      }).toList();

                                  setState(() {
                                    final existingSkuIndex = _skus.indexWhere((
                                      sku,
                                    ) {
                                      final specs =
                                          sku['specs']
                                              as List<Map<String, dynamic>>;
                                      return specs.every(
                                        (spec) =>
                                            _selectedSpecValues[spec['id']] ==
                                            spec['value'],
                                      );
                                    });

                                    if (existingSkuIndex != -1) {
                                      _skus[existingSkuIndex]['image'] = value;
                                    } else {
                                      _skus.add({
                                        'specs': specCombination,
                                        'stock':
                                            int.tryParse(
                                              _stockController.text,
                                            ) ??
                                            1000,
                                        'price': double.tryParse(
                                          _priceController.text,
                                        ),
                                        'image': value,
                                      });
                                    }
                                  });
                                }
                              },
                              validator:
                                  (value) =>
                                      value == null && _attrNames.isNotEmpty
                                          ? '请选择图片'
                                          : null,
                            ),
                          ],
                        ),
                      const SizedBox(height: 16),
                      TextFormField(
                        controller: _descriptionController,
                        decoration: const InputDecoration(
                          labelText: '详情',
                          border: OutlineInputBorder(),
                        ),
                        maxLines: 5,
                        onSaved: (value) => _description = value ?? '',
                      ),
                      const SizedBox(height: 16),
                      DropdownButtonFormField<SpuStatus>(
                        value: _status,
                        decoration: const InputDecoration(
                          labelText: '状态*',
                          border: OutlineInputBorder(),
                        ),
                        items:
                            SpuStatus.values.map((SpuStatus status) {
                              return DropdownMenuItem<SpuStatus>(
                                value: status,
                                child: Text(
                                  status == SpuStatus.toEnable
                                      ? '待上架'
                                      : status == SpuStatus.disabled
                                      ? '已下架'
                                      : '销售中',
                                ),
                              );
                            }).toList(),
                        validator: (value) => value == null ? '状态不能为空' : null,
                        onChanged: (value) {
                          setState(() {
                            _status = value ?? SpuStatus.toEnable;
                          });
                        },
                        onSaved: (value) => _status = value!,
                      ),
                      const SizedBox(height: 32),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          ElevatedButton(
                            onPressed: _resetForm,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.grey[300],
                              foregroundColor: Colors.black87,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              elevation: 0,
                            ),
                            child: const Text('重置'),
                          ),
                          const SizedBox(width: 16),
                          ElevatedButton(
                            onPressed: _submitForm,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: const Color(0xFF1A73E8),
                              foregroundColor: Colors.white,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              elevation: 0,
                            ),
                            child: const Text('确定'),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
    );
  }
}
